package ai.loa.framework.controller;

import java.util.List;

import ai.loa.ai.Mossa;
import ai.loa.ai.Stato;
import ai.loa.framework.LOABoard;
import ai.loa.utility.TraspositionTables;

public class LocalLOAController extends LOAController {

	public LocalLOAController(int player) {
		stato = new Stato((byte) player);
	}

	// public Stato stato;
	private LOAGameObserver[] observers = new LOAGameObserver[2];;

	private void switchPlayer() {
		stato.player = (byte) ((stato.player + 1) % 2);
		stato.turno++;
	}

	public boolean doMove(Mossa move) {
		String s = "";
		if (move.player == LOABoard.PLAYER_1) {
			s += "Il giocatore bianco muove: ";
		} else {
			s += "Il giocatore nero muove: ";
		}
		s += move;
		System.out.println(s);
		// StreamsForDebug.logGame.println(s);
		// StreamsForDebug.logGame.flush();
		stato.board[move.cellStartX][move.cellStartY] = LOABoard.VUOTO;
		stato.board[move.cellDestX][move.cellDestY] = (byte) move.player;
		TraspositionTables c = TraspositionTables.getInstance();
		if (move.mangia) {
			stato.piecesInGame[(move.player + 1) % 2]--;
			stato.zKey ^= c.cacheMatrix[move.player][move.cellStartX][move.cellStartY];
			stato.zKey ^= c.cacheMatrix[move.player][move.cellDestX][move.cellDestY];
			stato.zKey ^= c.invTurno;
			stato.zKey ^= c.cacheMatrix[(move.player + 1) % 2][move.cellDestX][move.cellDestY];
		} else {
			stato.zKey ^= c.cacheMatrix[move.player][move.cellStartX][move.cellStartY];
			stato.zKey ^= c.cacheMatrix[move.player][move.cellDestX][move.cellDestY];
			stato.zKey ^= c.invTurno;
		}
		stato.updateDirezioneCasella(move.cellDestX, move.cellDestY);
		stato.updateDirezioneCasella(move.cellStartX, move.cellStartY);
		// stato.updateBaricentro();
		switchPlayer();
		// IndependentFeatures.save();
		notifyPlayer(stato.player);
		// System.out.println("CONNECTEDNESS: "+stato.myConnectedness);
		return true;
	}

	public int winner() {
		return stato.isFoglia();
	}

	public void stampaMosseLegali() {
		List<Mossa> l = stato.mosseLegali();
		for (Mossa mossa : l) {
			System.out.println(mossa);
		}
	}

	public int getCurrentPlayer() {
		return stato.player;
	}

	public void setObserver(LOAGameObserver o, int player) {
		observers[player] = o;
	}

	protected void notifyPlayer(int player) {
		observers[player].turnChanged(stato);
	}

	public void startGame() {
		notifyPlayer(stato.player);
	}
}
